package com.example.application.views.upload;

import com.vaadin.flow.component.*;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MultiFileMemoryBuffer;
import com.vaadin.flow.internal.MessageDigestUtil;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.StreamResource;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.StringBuilders;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;

@Route("upload")
@PageTitle("文件操作")
public class PhotoView extends Div {

    private TextField username;
    private Label label;
    private Button button;

    public PhotoView(){
        label = new Label("姓名");
        username = new TextField();
        username.setPlaceholder("请输入姓名");

        MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();

        Upload upload = new Upload(buffer);
        //upload.setAutoUpload(false);
        Div output = new Div();
        output.setWidth("100px");
        output.setHeight("100px");
        upload.addSucceededListener(event -> {
            Component component = createComponent(event.getMIMEType(),
                    event.getFileName(),
                    buffer.getInputStream(event.getFileName()));
            showOutput(event.getFileName(), component, output);
            //上传图片到本地服务器
            InputStream inputStream =buffer.getInputStream(event.getFileName());

            System.out.println(System.getProperty("user.dir")+"\\src\\main\\resources\\photo\\"+"---------------");
            //写本地服务器
            File file = new File(System.getProperty("user.dir")+"\\src\\main\\resources\\photo\\");
            if(!file.exists()){
                file.mkdir();
            }
            //获得文件的新名字
            String newFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmss"))+event.getFileName().substring(event.getFileName().lastIndexOf("."));
            //设置最终保存文件的地址
            String save_path = System.getProperty("user.dir")+"/src/main/resources/photo/"+newFileName;
             //写
            byte[] buf = new byte[1024];
            int len=0;
            OutputStream out=null;

            try {
                 out = new FileOutputStream(new File(save_path));

                while( (len=inputStream.read(buf,0,buf.length))!=-1){

                    out.write(buf,0,len);
                }
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            //往后台发送文件
            try(CloseableHttpClient client = HttpClients.createDefault()){
                HttpPost httpPost =new HttpPost("http://127.0.0.1:8888/ssm/upload");
                FileBody fileBody = new FileBody(new File(save_path));
                StringBody stringBody = new StringBody(username.getValue(), ContentType.TEXT_PLAIN);
                HttpEntity reqEntity = MultipartEntityBuilder.create()
                        .addPart("myfile", fileBody)
                        .addPart("username", stringBody)
                        .build();
                httpPost.setEntity(reqEntity);
                CloseableHttpResponse resp = client.execute(httpPost);
                String  up = EntityUtils.toString(resp.getEntity(),"utf-8");
                System.out.println(up);

            }catch (Exception e){
                e.printStackTrace();
            }


        });
        upload.getElement().addEventListener("file-remove", event -> {
            output.removeAll();
        });
        button = new Button("提交");
        button.getStyle().set("margin-top","50px");
        add(label,username,upload,output,button);

    }

    private Component createComponent(String mimeType, String fileName,
                                      InputStream stream) {
        if (mimeType.startsWith("text")) {
            return createTextComponent(stream);
        } else if (mimeType.startsWith("image")) {
            Image image = new Image();
            try {

                byte[] bytes = IOUtils.toByteArray(stream);
                image.getElement().setAttribute("src", new StreamResource(
                        fileName, () -> new ByteArrayInputStream(bytes)));
                try (ImageInputStream in = ImageIO.createImageInputStream(
                        new ByteArrayInputStream(bytes))) {
                    final Iterator<ImageReader> readers = ImageIO
                            .getImageReaders(in);
                    if (readers.hasNext()) {
                        ImageReader reader = readers.next();
                        try {
                            reader.setInput(in);
                            image.setWidth(reader.getWidth(0) + "px");
                            image.setHeight(reader.getHeight(0) + "px");
                        } finally {
                            reader.dispose();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.setSizeFull();
            return image;
        }
        Div content = new Div();
        String text = String.format("Mime type: '%s'\nSHA-256 hash: '%s'",
                mimeType, MessageDigestUtil.sha256(stream.toString()));
        content.setText(text);
        return content;

    }

    private Component createTextComponent(InputStream stream) {
        String text;
        try {
            text = IOUtils.toString(stream, StandardCharsets.UTF_8);
        } catch (IOException e) {
            text = "exception reading stream";
        }
        return new Text(text);
    }

    private void showOutput(String text, Component content,
                            HasComponents outputContainer) {
        HtmlComponent p = new HtmlComponent(Tag.P);
        p.getElement().setText(text);
        outputContainer.add(p);
        outputContainer.add(content);
    }



}
